<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-09-22
 * @Time: 15:38
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Exam.php
 */
namespace app\api\model\curriculum;

use think\Db;
use think\Model;

class Exam extends Model {
    /**
     * get_video_questions
     * 获取课程视频测试题目（随机10道）
     *
     * @author zhengkai
     * @date 2017-09-22
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     * @param int $video_id 视频id
     * @return \think\response\Json
     */
    public function get_video_questions($uid, $curriculum_id, $video_id)
    {
        // 查询课程视频测试
        $exam = Db::query("select exam_id,exam_duration from curriculum_exam where exam_curriculum={$curriculum_id} and exam_video={$video_id}");
        if (!$exam) return json(array('code'=>200, 'msg'=>'success', 'data'=>(object)[]));
        $exam = $exam[0];

        // 查询用户是第几次参与测试
        $exam_num = Db::query("select count(score_id) as exam_num from user_exam_score where score_user={$uid} and score_curriculum={$curriculum_id} and score_video={$video_id}");
        $exam_num = $exam_num[0]['exam_num'];
        $exam['exam_num'] = ++$exam_num;

        // 查询课程视频测试题（随机10条）
        $questions = Db::query("
select q.questions_id,q.questions_type,q.questions_title,q.questions_content,q.questions_option,q.questions_scores,q.option_content_type from curriculum_exam_questions ceq
  left join questions q on (ceq.eq_questions=q.questions_id)
where ceq.eq_exam={$exam['exam_id']}
order by RANDOM() limit 10
");
        foreach ($questions as &$val) {
            $val['questions_option'] = json_decode($val['questions_option'], true);
        }

        $exam['questions'] = $questions;

        $resutl = $exam;

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$resutl));
    }

    /**
     * insert_questions_answer
     * 课程视频测试结果写入数据库并进行相关数据处理
     *
     * @author zhengkai
     * @date 2017-09-25
     *
     * @param int $uid 用户id
     * @param string $getData 需要提交的参数
     * @return \think\response\Json
     */
    public function insert_questions_answer($uid, $getData)
    {
        $setData = json_decode($getData, true);

        /*$testData = <<<EOT
  {
    "exam_id": 3,
    "exam_num": 7,
    "curriculum_id": 4,
    "video_id": 20,
    "questions": [
      {
        "questions_id": 2,
        "questions_answer": "A"
      },
      {
        "questions_id": 5,
        "questions_answer": "D"
      },
      {
        "questions_id": 6,
        "questions_answer": "C"
      },
      {
        "questions_id": 7,
        "questions_answer": "C"
      },
      {
        "questions_id": 10,
        "questions_answer": "BC"
      },
      {
        "questions_id": 11,
        "questions_answer": "B"
      },
      {
        "questions_id": 9,
        "questions_answer": "B"
      }
    ]
  }
EOT;
        $testData = json_decode($testData, true);*/

        // 开启事务
        Db::startTrans();
        try {
            foreach ($setData['questions'] as $key=>$val) {
                // 查询出测试题目的正确答案与分值
                $questions = Db::query("
select q.questions_id, q.questions_answer, questions_scores from curriculum_exam_questions ceq
  left join questions q on (ceq.eq_questions=q.questions_id)
where ceq.eq_exam={$setData['exam_id']} and ceq.eq_questions={$val['questions_id']}
");
                $questions = $questions[0];
                $questions['questions_answer'] = json_decode($questions['questions_answer'], true);
                if (is_array($questions['questions_answer'])) $questions['questions_answer'] = implode('', $questions['questions_answer']);

                // 判断答题正误
                if ($val['questions_answer']==$questions['questions_answer']) {
                    // 正确
                    $user_scores = $questions['questions_scores'];
                } else {
                    // 错误
                    $user_scores = 0;
                }

                $data = [
                    'el_user' => $uid, // 用户id
                    'el_exam' => $setData['exam_id'], // 测试id
                    'el_num' => $setData['exam_num'], // 用户第几次参数测试
                    'el_questions' => $val['questions_id'], // 题目id
                    'el_score' => $user_scores, // 答题得分
                    'el_user_answer' => $val['questions_answer'], // 用户答案
                    'el_questions_answer' => $questions['questions_answer'] // 正确答案
                ];

                Db::table('user_exam_log')->insert($data);
            }

            // 统计测试总分
            $totalScore = Db::query("
select COALESCE(sum(el_score), 0) as score from user_exam_log 
where el_num={$setData['exam_num']} and el_user={$uid} and el_exam={$setData['exam_id']}
");
            $totalScore = $totalScore[0]['score'];

            $data = [
                'score_user' => $uid, // 用户id
                'score_curriculum' => $setData['curriculum_id'], // 课程id
                'score_video' => $setData['video_id'], // 课程视频id
                'score_total' => $totalScore, // 测试总得分
                'score_time' => time()
            ];
            Db::table('user_exam_score')->insert($data);

            // 查询测试的课程视频的难度级别
            $video_level = Db::query("select video_level from curriculum_video where video_id={$setData['video_id']}");
            $video_level = $video_level[0]['video_level'];

            // 更新课程视频学习状态
            if ($totalScore >= 60) {
                Db::table('user_study_video')
                    ->where('usv_user', $uid)
                    ->where('usv_curriculum', $setData['curriculum_id'])
                    ->where('usv_video', $setData['video_id'])
                    ->where('usv_video_level', $video_level)
                    ->where('usv_study_status', '=', 1)
                    ->update([
                        'usv_study_status'=>2,
                        'usv_study_updatetime'=>time()
                    ]);
            }

            // 获取课程视频的个数
            $video_num = Db::query("select count(video_id) as video_num  from curriculum_video where video_curriculum={$setData['curriculum_id']} and video_level={$video_level}");
            $video_num = $video_num[0]['video_num'];

            // 统计已参与测试并且合格的课程视频数量
            $exam_pass_video = Db::query("
select count(distinct(ues.score_video)) as video_num from user_exam_score ues
  left join curriculum_video cv on (ues.score_video=cv.video_id)
where cv.video_level={$video_level} and ues.score_total>=60 and ues.score_user={$uid}
");
            $exam_pass_num = $exam_pass_video[0]['video_num'];

            // 判断已测试通过的课程视频是否与发布的课程视频数据相等
            if ($exam_pass_num==$video_num) {
                switch ($video_level) {
                    case 1:
                        $unlock_level = 2;
                        break;
                    case 2:
                    case 3:
                        $unlock_level = 3;
                        break;
                }

                // 查询下个难度等级课程视频是否已被标记为可解锁或者已解锁状态
                $next_level_status = Db::query("
select ucl_level_lock from user_buy_curriculum_level 
where ucl_user={$uid} and ucl_curriculum={$setData['curriculum_id']} and ucl_level={$unlock_level}
");
                $next_level_status = $next_level_status[0]['ucl_level_lock'];

                if ($next_level_status>0) {
                    $is_unlock_next_level = 2;
                } else {
                    // 所有课程视频测试通过后将下个难度等级视频标记为可解锁状态
                    Db::table('user_buy_curriculum_level')
                        ->where('ucl_user', $uid)
                        ->where('ucl_curriculum', $setData['curriculum_id'])
                        ->where('ucl_level', '=', $unlock_level)
                        ->where('ucl_level_lock', '=', 0)
                        ->update([
                            'ucl_level_lock'=>1
                        ]);
                    $is_unlock_next_level = 1;
                }

            } else {
                $is_unlock_next_level = 0;
            }

            // 提交事务
            Db::commit();

            $result = [
                'is_pass' => $totalScore>=60 ? 1 : 0, // 是否通过测试
                'exam_score' => $totalScore, // 测试得分
                'is_unlock_next_level' => $is_unlock_next_level // 是否解锁下一课程视频难度等级
            ];
            return json(array('code'=>200, 'msg'=>'提交成功', 'data'=>$result));
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();

            return json(array('code'=>1012, 'msg'=>'提交失败', 'data'=>null));
        }
    }
}